<template>
  <view class="shop-detail-container">
    <!-- 顶部搜索栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input type="text" placeholder="请输入商品名称" />
      </view>
    </view>
    
    <!-- 店铺信息 -->
    <view class="shop-info">
      <image :src="shop.imgUrl" mode="aspectFill"></image>
      <view class="shop-data">
        <text class="shop-name">{{shop.name}}</text>
        <view class="shop-stats">
          <text>月售：{{shop.sales}}</text>
          <text>起送：{{shop.expressLimit}}</text>
          <text>基础运费：{{shop.expressPrice}}</text>
        </view>
        <text class="shop-slogan">{{shop.slogan}}</text>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <view class="product-list">
      <view class="product-item" v-for="(product, index) in products" :key="index">
        <image :src="product.imgUrl" mode="aspectFill"></image>
        <view class="product-info">
          <text class="product-name">{{product.name}}</text>
          <text class="product-sales">月售 {{product.sales}} 件</text>
          <view class="product-price">
            <text class="current-price">¥{{product.price}}</text>
            <text class="old-price" v-if="product.oldPrice">¥{{product.oldPrice}}</text>
            <view class="quantity-control">
              <text class="minus" v-if="cartProducts[product._id]" @click.stop="decreaseCart(product)">-</text>
              <text class="count" v-if="cartProducts[product._id]">{{cartProducts[product._id]}}</text>
              <text class="plus" @click.stop="addToCart(product)">+</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部购物车 -->
    <view class="cart-bar" v-if="Object.keys(cartProducts).length > 0">
      <view class="cart-icon" @click="toggleCartPopup">
        <image src="/static/icon/购物车空.png" mode="aspectFit" style="width: 60rpx; height: 60rpx;"></image>
        <view class="cart-count">{{getTotalCount}}</view>
      </view>
      <view class="cart-price">
        <text>总计: ¥ {{getTotalPrice.toFixed(2)}}</text>
      </view>
      <view class="checkout-btn" @click="goToOrderConfirm">
        去结算
      </view>
    </view>
    
    <!-- 购物车弹窗 -->
    <view class="cart-popup" v-if="showCartPopup">
      <view class="cart-popup-mask" @click="toggleCartPopup"></view>
      <view class="cart-popup-content">
        <view class="cart-popup-header">
          <text class="cart-popup-title">购物车</text>
          <text class="cart-popup-clear" @click="clearCart">清空购物车</text>
        </view>
        
        <scroll-view scroll-y class="cart-popup-list">
          <view class="cart-popup-item" v-for="(product) in cartProductsList" :key="product._id">
            <view class="cart-popup-item-info">
              <image :src="product.imgUrl" mode="aspectFill"></image>
              <view class="cart-popup-item-detail">
                <text class="cart-popup-item-name">{{product.name}} {{product.weight || ''}}</text>
                <view class="cart-popup-item-price">
                  <text class="price">¥{{product.price}}</text>
                  <text class="old-price" v-if="product.oldPrice">¥{{product.oldPrice}}</text>
                </view>
              </view>
            </view>
            <view class="quantity-control">
              <text class="minus" @click.stop="decreaseCart(product)">-</text>
              <text class="count">{{cartProducts[product._id]}}</text>
              <text class="plus" @click.stop="addToCart(product)">+</text>
            </view>
          </view>
        </scroll-view>
        
        <view class="cart-popup-footer">
          <view class="cart-popup-total">
            <text>合计: ¥ {{getTotalPrice.toFixed(2)}}</text>
          </view>
          <view class="cart-popup-checkout" @click="goToOrderConfirm">
            去结算({{getTotalCount}})
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopId: '',
      shop: {
        name: '',
        imgUrl: '',
        sales: 0,
        expressLimit: 0,
        expressPrice: 5,
        slogan: ''
      },
      products: [],
      cartProducts: {},
      showCartPopup: false
    }
  },
  computed: {
    getTotalCount() {
      return Object.values(this.cartProducts).reduce((a, b) => a + b, 0);
    },
    getTotalPrice() {
      let total = 0;
      for (const productId in this.cartProducts) {
        const product = this.products.find(p => p._id === productId);
        if (product) {
          total += product.price * this.cartProducts[productId];
        }
      }
      return total;
    },
    cartProductsList() {
      const list = [];
      for (const productId in this.cartProducts) {
        const product = this.products.find(p => p._id === productId);
        if (product) {
          list.push({
            ...product,
            count: this.cartProducts[productId]
          });
        }
      }
      return list;
    }
  },
  onLoad(options) {
    this.shopId = options.id || '';
    this.loadShopData();
    this.loadProducts();
    this.loadCartData();
  },
  methods: {
    loadShopData() {
      uni.request({
        url: 'http://localhost:3000/hotList',
        success: (res) => {
          if (res.statusCode === 200) {
            const shop = res.data.find(item => item._id === this.shopId);
            if (shop) {
              this.shop = shop;
            }
          }
        }
      });
    },
    loadProducts() {
      uni.request({
        url: 'http://localhost:3000/products-all',
        success: (res) => {
          if (res.statusCode === 200) {
            this.products = res.data.filter(item => item.shopId === this.shopId);
            this.loadCartData();
          }
        }
      });
    },
    loadCartData() {
      // 加载全局购物车数据
      const globalCart = JSON.parse(uni.getStorageSync('cartData') || '{}');
      
      // 筛选当前店铺的商品
      this.cartProducts = {};
      for (const productId in globalCart) {
        const product = this.products.find(p => p._id === productId);
        if (product && product.shopId === this.shopId) {
          this.cartProducts[productId] = globalCart[productId];
        }
      }
    },
    addToCart(product) {
      // 获取全局购物车
      const globalCart = JSON.parse(uni.getStorageSync('cartData') || '{}');
      
      // 更新数量
      if (!globalCart[product._id]) {
        globalCart[product._id] = 0;
      }
      globalCart[product._id]++;
      
      // 保存到全局和本地
      uni.setStorageSync('cartData', JSON.stringify(globalCart));
      this.cartProducts = {...this.cartProducts, [product._id]: globalCart[product._id]};
      
      // 触发更新事件
      uni.$emit('cart-updated', {
        productId: product._id,
        count: globalCart[product._id]
      });
      
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
    },
    decreaseCart(product) {
      // 获取全局购物车
      const globalCart = JSON.parse(uni.getStorageSync('cartData') || '{}');
      
      if (globalCart[product._id] > 0) {
        globalCart[product._id]--;
        
        if (globalCart[product._id] === 0) {
          delete globalCart[product._id];
          const newCart = {...this.cartProducts};
          delete newCart[product._id];
          this.cartProducts = newCart;
        } else {
          this.cartProducts = {...this.cartProducts, [product._id]: globalCart[product._id]};
        }
        
        // 保存到全局
        uni.setStorageSync('cartData', JSON.stringify(globalCart));
        
        // 触发更新事件
        uni.$emit('cart-updated', {
          productId: product._id,
          count: globalCart[product._id] || 0
        });
      }
    },
    toggleCartPopup() {
      this.showCartPopup = !this.showCartPopup;
    },
    clearCart() {
      uni.showModal({
        title: '提示',
        content: '确定要清空购物车吗？',
        success: (res) => {
          if (res.confirm) {
            // 获取全局购物车
            const globalCart = JSON.parse(uni.getStorageSync('cartData') || '{}');
            
            // 移除当前店铺的商品
            for (const productId in this.cartProducts) {
              delete globalCart[productId];
            }
            
            // 保存全局购物车
            uni.setStorageSync('cartData', JSON.stringify(globalCart));
            
            // 清空本地购物车
            this.cartProducts = {};
            this.showCartPopup = false;
            
            // 触发更新事件
            uni.$emit('cart-cleared');
            
            uni.showToast({
              title: '购物车已清空',
              icon: 'success'
            });
          }
        }
      });
    },
   // 商品详情页中的方法
goToOrderConfirm() {
  if (this.getTotalCount === 0) {
    uni.showToast({
      title: '购物车为空',
      icon: 'none'
    });
    return;
  }
  
  // 准备结算数据
  const checkoutProducts = [];
  for (const productId in this.cartProducts) {
    const product = this.products.find(p => p._id === productId);
    if (product) {
      checkoutProducts.push({
        ...product,
        count: this.cartProducts[productId]
      });
    }
  }
  
  // 保存店铺信息到本地存储
  uni.setStorageSync('shopInfo', JSON.stringify(this.shop));
  
  // 保存购物车数据到本地存储
  const cartData = {};
  checkoutProducts.forEach(product => {
    cartData[product._id] = product.count;
  });
  uni.setStorageSync('cartData', JSON.stringify(cartData));
  
  // 跳转到确认订单页面
  uni.navigateTo({
    url: '/pages/order/order-confirm'
  });
},
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss">
.shop-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  
  .back-btn {
    margin-right: 20rpx;
  }
  
  .search-box {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 30rpx;
    padding: 10rpx 20rpx;
    
    input {
      flex: 1;
      font-size: 26rpx;
      margin-left: 10rpx;
    }
  }
}

.shop-info {
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  
  image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
  }
  
  .shop-data {
    flex: 1;
    
    .shop-name {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .shop-stats {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10rpx;
      
      text {
        font-size: 24rpx;
        color: #666;
        margin-right: 20rpx;
      }
    }
    
    .shop-slogan {
      font-size: 24rpx;
      color: #ff6b6b;
    }
  }
}

.product-list {
  padding: 20rpx;
  
  .product-item {
    display: flex;
    padding: 20rpx;
    background-color: #fff;
    margin-bottom: 20rpx;
    border-radius: 12rpx;
    
    image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }
    
    .product-info {
      flex: 1;
      position: relative;
      
      .product-name {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }
      
      .product-sales {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 20rpx;
      }
      
      .product-price {
        display: flex;
        align-items: center;
        
        .current-price {
          font-size: 32rpx;
          color: #ff6b6b;
          font-weight: bold;
          margin-right: 10rpx;
        }
        
        .old-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
        
        .quantity-control {
          position: absolute;
          right: 0;
          bottom: 0;
          display: flex;
          align-items: center;
          
          .minus, .plus {
            width: 50rpx;
            height: 50rpx;
            line-height: 46rpx;
            text-align: center;
            border-radius: 50%;
            border: 1rpx solid #eee;
            font-size: 28rpx;
          }
          
          .count {
            margin: 0 20rpx;
            font-size: 28rpx;
          }
          
          .plus {
            background-color: #0086ff;
            color: #fff;
            border: none;
          }
        }
      }
    }
  }
}

.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .cart-icon {
    position: relative;
    margin-right: 20rpx;
    
    .cart-count {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      background-color: #ff6b6f;
      color: #fff;
      font-size: 20rpx;
      width: 36rpx;
      height: 36rpx;
      border-radius: 50%;
      text-align: center;
      line-height: 36rpx;
    }
  }
  
  .cart-price {
    flex: 1;
    font-size: 28rpx;
  }
  
  .checkout-btn {
    background-color: #0086ff;
    color: #fff;
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    font-size: 28rpx;
  }
}

.cart-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  
  .cart-popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }
  
  .cart-popup-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    max-height: 70vh;
    display: flex;
    flex-direction: column;
    
    .cart-popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      .cart-popup-title {
        font-size: 32rpx;
        font-weight: bold;
      }
      
      .cart-popup-clear {
        font-size: 26rpx;
        color: #999;
      }
    }
    
    .cart-popup-list {
      flex: 1;
      max-height: 50vh;
      padding: 0 30rpx;
      
      .cart-popup-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;
        
        .cart-popup-item-info {
          display: flex;
          align-items: center;
          flex: 1;
          
          image {
            width: 120rpx;
            height: 120rpx;
            border-radius: 8rpx;
            margin-right: 20rpx;
          }
          
          .cart-popup-item-detail {
            flex: 1;
            
            .cart-popup-item-name {
              font-size: 28rpx;
              margin-bottom: 10rpx;
            }
            
            .cart-popup-item-price {
              .price {
                font-size: 30rpx;
                color: #ff6b6b;
                font-weight: bold;
              }
              
              .old-price {
                font-size: 24rpx;
                color: #999;
                text-decoration: line-through;
                margin-left: 10rpx;
              }
            }
          }
        }
        
        .quantity-control {
          display: flex;
          align-items: center;
          
          .minus, .plus {
            width: 50rpx;
            height: 50rpx;
            line-height: 46rpx;
            text-align: center;
            border: 1rpx solid #eee;
            border-radius: 50%;
            font-size: 28rpx;
          }
          
          .minus {
            color: #999;
          }
          
          .plus {
            color: #0086ff;
            border-color: #0086ff;
          }
          
          .count {
            margin: 0 20rpx;
            font-size: 28rpx;
          }
        }
      }
    }
    
    .cart-popup-footer {
      display: flex;
      align-items: center;
      padding: 20rpx 30rpx;
      border-top: 1rpx solid #f5f5f5;
      
      .cart-popup-total {
        flex: 1;
        font-size: 30rpx;
        font-weight: bold;
      }
      
      .cart-popup-checkout {
        background-color: #0086ff;
        color: #fff;
        padding: 15rpx 30rpx;
        border-radius: 30rpx;
        font-size: 28rpx;
      }
    }
  }
}
</style>